/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.LockSupport;

/**
 * A cancellable asynchronous computation.  This class provides a base
 * implementation of {@link Future}, with methods to start and cancel
 * a computation, query to see if the computation is complete, and
 * retrieve the result of the computation.  The result can only be
 * retrieved when the computation has completed; the {@code get}
 * methods will block if the computation has not yet completed.  Once
 * the computation has completed, the computation cannot be restarted
 * or cancelled (unless the computation is invoked using
 * {@link #runAndReset}).
 * 一个可取消的异步计算。该类提供了{@link Future}的基本实现，其中包含启动和取消计算的方法，查询计算是否完成以及检索计算结果的方法。
 * 只有当计算完成时，才能检索到结果；如果计算尚未完成，{@code get}方法将会阻塞。
 * 一旦计算完成，就不能重新启动或取消计算（除非使用{@link #runAndReset}来调用计算）。
 *
 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
 * {@link Runnable} object.  Because {@code FutureTask} implements
 * {@code Runnable}, a {@code FutureTask} can be submitted to an
 * {@link Executor} for execution.
 *
 * <p>In addition to serving as a standalone class, this class provides
 * {@code protected} functionality that may be useful when creating
 * customized task classes.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this FutureTask's {@code get} methods
 */
public class FutureTask<V> implements RunnableFuture<V> {
    /*
     * Revision notes: This differs from previous versions of this
     * class that relied on AbstractQueuedSynchronizer, mainly to
     * avoid surprising users about retaining interrupt status during
     * cancellation races. Sync control in the current design relies
     * on a "state" field updated via CAS to track completion, along
     * with a simple Treiber stack to hold waiting threads.
     *
     * Style note: As usual, we bypass overhead of using
     * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics.
     * 修订说明：这与该类的先前版本有所不同，先前版本依赖于AbstractQueuedSynchronizer，主要是为了避免在取消竞争期间保留中断状态时令用户感到惊讶。
     * 在当前设计中，同步控制依赖于通过CAS更新的"state"字段来跟踪完成情况，并且使用简单的Treiber栈来保存等待的线程。
     * 风格注释：通常情况下，我们绕过使用AtomicXFieldUpdaters的开销，而是直接使用Unsafe的内部函数。
     */

    /**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * 可能的状态过度只有以下几种
     * 有一点需要注意的是，所有值大于COMPLETING的状态都表示任务已经执行完成(任务正常执行完成，任务执行异常或者任务被取消)。
     * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    private volatile int state;
    /** 表示是个新的任务或者还没被执行完的任务。这是初始状态。 */
    private static final int NEW          = 0;
    /**
     * 任务已经执行完成或者执行任务的时候发生异常，但是任务执行结果或者异常原因还没有保存到outcome字段
     * (outcome字段用来保存任务执行结果，如果发生异常，则用来保存异常原因)的时候，状态会从NEW变更到COMPLETING。
     * 这个状态会时间会比较短，属于中间状态。
     */
    private static final int COMPLETING   = 1;
    /**
     * 任务已经执行完成并且任务执行结果已经保存到outcome字段，状态会从COMPLETING转换到NORMAL。这是一个最终态。
     */
    private static final int NORMAL       = 2;
    /**
     * 任务执行发生异常并且异常原因已经保存到outcome字段中后，状态会从COMPLETING转换到EXCEPTIONAL。这是一个最终态。
     */
    private static final int EXCEPTIONAL  = 3;
    /**
     * 任务还没开始执行或者已经开始执行但是还没有执行完成的时候，用户调用了cancel(false)方法取消任务且不中断任务执行线程，
     * 这个时候状态会从NEW转化为CANCELLED状态。这是一个最终态。
     */
    private static final int CANCELLED    = 4;
    /**
     * 任务还没开始执行或者已经执行但是还没有执行完成的时候，用户调用了cancel(true)方法取消任务并且要中断任务执行线程但是还没有中断任务执行线程之前，
     * 状态会从NEW转化为INTERRUPTING。这是一个中间状态。
     */
    private static final int INTERRUPTING = 5;
    /**
     * 调用interrupt()中断任务执行线程之后状态会从INTERRUPTING转换到INTERRUPTED。这是一个最终态。
     */
    private static final int INTERRUPTED  = 6;

    /** 将要执行的任务 */
    private Callable<V> callable;
    /** 从 get() 返回的结果或抛出的异常 */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** 运行可调用的线程；在 run() 期间被 CASed */
    private volatile Thread runner;
    /** 等待线程的 队列头部：最新的 */
    private volatile WaitNode waiters;

    /**
     * 为完成的任务返回结果或抛出异常。
     * 根据状态决定是正常执行结束了还是任务被取消了（如发生异常或者被中断）
     *
     * @param s completed state value
     */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        //任务正常执行结束
        if (s == NORMAL)
            return (V)x;
        //任务被取消了
        if (s >= CANCELLED)
            throw new CancellationException();
        //执行过程中发生了异常
        throw new ExecutionException((Throwable)x);
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable 确保callable的可见性（第二个操作是volatile写，无论第一个操作是什么都不允许重排序）
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     * 创建一个FutureTask，在运行时将执行给定的Runnable，并安排在成功完成时get方法将返回给定的结果。
     *
     * @param runnable the runnable task
     * @param result the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * 在成功完成时返回的结果。如果您不需要特定的结果，考虑使用以下形式的构造方式：
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable 确保callable的可见性（第二个操作是volatile写，无论第一个操作是什么都不允许重排序）
    }

    /**
     * 判断任务是否被取消
     */
    public boolean isCancelled() {
        return state >= CANCELLED;
    }

    /**
     * 判断任务是否已经完成，如果完成则返回true，否则返回false。需要注意的是：任务执行过程中发生异常、任务被取消也属于任务已完成，也会返回true。
     */
    public boolean isDone() {
        return state != NEW;
    }

    /**
     * 注意：
     * cancel方法无论mayInterruptIfRunning是true还是false都不会真正停止任务的执行，
     * 当且仅当mayInterruptIfRunning为true且被中断的线程感知中断信号自己主动停止时才能停止任务的执行。
     *
     * 用来取消异步任务的执行。如果异步任务已经完成或者已经被取消，或者由于某些原因不能取消，则会返回false。
     * 如果任务还没有被执行，则会返回true并且异步任务不会被执行。
     * 如果任务已经开始执行了但是还没有执行完成，若mayInterruptIfRunning为true，则会立即中断执行任务的线程并返回true（只是给个中断信号，是否停止执行还需要执行逻辑自己获取状态去处理）
     * 若mayInterruptIfRunning为false，则会返回true且不会中断任务执行线程。
     */
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            //说明任务已经执行完了 正常执行完毕或者异常执行完毕
            return false;
        try {
            //进入到这里说明任务要么处于中间状态要么执行完毕了
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        //发送中断信号
                        t.interrupt();
                } finally { // final state
                    //从INTERRUPTING 改为 INTERRUPTED
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

    /**
     * 任务发起线程可以调用get()方法来获取任务执行结果，如果任务还没完成则会阻塞等待直到任务执行完成。
     * 如果任务被取消则会抛出CancellationException异常，
     * 如果任务执行过程发生异常则会抛出ExecutionException异常，
     * 如果阻塞等待过程中被中断则会抛出InterruptedException异常。
     */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            //无限阻塞等待任务完成（正常完成或者异常结束）
            s = awaitDone(false, 0L);
        return report(s);
    }

    /**
     * 带超时时间的get()版本，如果阻塞等待过程中超时则会抛出TimeoutException异常。
     */
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

    /**
     * Protected method invoked when this task transitions to state
     * {@code isDone} (whether normally or via cancellation). The
     * default implementation does nothing.  Subclasses may override
     * this method to invoke completion callbacks or perform
     * bookkeeping. Note that you can query status inside the
     * implementation of this method to determine whether this task
     * has been cancelled.
     *
     这是在任务转换到状态isDone（无论是正常完成还是通过取消）时调用的受保护方法。默认实现不执行任何操作。
     子类可以覆盖此方法来调用完成回调或执行簿记。请注意，您可以在此方法的实现内查询状态，以确定此任务是否已被取消。
     */
    protected void done() { }

    /**
     * Sets the result of this future to the given value unless
     * this future has already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon successful completion of the computation.
     *
     * @param v the value
     */
    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

    /**
     * Causes this future to report an {@link ExecutionException}
     * with the given throwable as its cause, unless this future has
     * already been set or has been cancelled.
     * 除非此Future已经被设置或已被取消，否则将导致此Future报告一个以给定throwable作为其原因的{@link ExecutionException}。
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon failure of the computation.
     * 此方法在计算失败时由{@link #run}方法内部调用。
     * @param t the cause of failure t表示失败的原因。
     */
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            //如果有再队列中等待获取结果的线程，那么这里会唤醒他们
            finishCompletion();
        }
    }

    public void run() {
        /**
         * 状态如果不是NEW：说明任务要么已经开始执行了，要么执行完毕了
         * 状态如果是NEW：那么需要防止有多个线程并发调用run方法，只允许一个线程能够去执行该任务
         */
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            //state == NEW不是冗余的而是必须的是为了保证任务只能被执行一次
            //假如
            //A时刻1线程和2线程同时拿到了state状态为NEW，
            //B时刻1线程成功CAS设置runner线程为1线程，2线程被CPU挂起
            //C时刻1线程执行完毕任务且执行完毕finally代码将runner设置为null
            //D时刻2线程获得CPU执行机会成功CAS设置runner线程为2线程，此时state肯定不为NEW了
            //所以state == NEW不是冗余的判断
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    // 发起Callable的调度，并获取返回值
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    //设置异常结果，改变状态
                    setException(ex);
                }
                if (ran) {
                    //设置正常结果，改变状态
                    set(result);
                }
            }
        } finally {
            // runner must be non-null until state is settled to prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            //如果任务被中断，执行中断处理
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

    /**
     * Executes the computation without setting its result, and then
     * resets this future to initial state, failing to do so if the
     * computation encounters an exception or is cancelled.  This is
     * designed for use with tasks that intrinsically execute more
     * than once.
     * 执行计算而不设置其结果，然后将此future重置为初始状态，如果计算遇到异常或被取消而未能成功重置，则会失败。
     * (runAndReset发生异常或者被中断的时候才会改变state的状态)
     * 这是为了与本质上需要执行多次的任务一起使用而设计的。
     * @return {@code true} if successfully run and reset
     */
    protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } finally {
            // runner must be non-null until state is settled to prevent concurrent calls to run()
            // 在状态被确定之前，runner 必须是非空的，以防止并发调用 run()。
            runner = null;
            // state must be re-read after nulling runner to prevent leaked interrupts
            // 在将 runner 设置为 null 后，必须重新读取 state，以防止泄漏的中断。
            // 这是为了确保在取消任务时，任务的状态仍然能够正确地反映任务是否已被取消，从而避免不必要的中断操作。
            // 重新读取 state 可以确保在 runner 被置为 null 之后仍然能够正确处理任务的状态。
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

    /**
     * Ensures that any interrupt from a possible cancel(true) is only delivered to a task while in run or runAndReset.
     * 确保从可能的cancel(true)产生的中断仅在任务处于run或runAndReset状态时传递给任务。
     */
    private void handlePossibleCancellationInterrupt(int s) {
        // It is possible for our interrupter to stall before getting a
        // chance to interrupt us.  Let's spin-wait patiently.
        // 在中断程序有机会中断我们之前，我们的中断程序可能会停顿。让我们耐心地自旋等待。
        if (s == INTERRUPTING)
            while (state == INTERRUPTING)
                Thread.yield(); // wait out pending interrupt

        // assert state == INTERRUPTED;

        // We want to clear any interrupt we may have received from
        // cancel(true).  However, it is permissible to use interrupts
        // as an independent mechanism for a task to communicate with
        // its caller, and there is no way to clear only the
        // cancellation interrupt.
        //
        // Thread.interrupted();
    }

    /**
     * 用于记录等待线程的简单链表节点。有关更详细的说明，请参阅其他类，例如 Phaser 和 SynchronousQueue。
     */
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

    /**
     * 唤醒等待获取结果的waiters并顺手做清理工作
     */
    private void finishCompletion() {
        // assert state > COMPLETING;
        //第一层for在这里的意思就是一个if
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        //唤醒等待线程
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    //没有后继节点了则跳出内存for
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        //用来拓展  比如ExecutorCompletionService在任务完成后添加进了一个队列，用来快速感知任务完成
        done();

        //最终会将callable置为null
        callable = null;        // to reduce footprint
    }

    /**
     * Awaits completion or aborts on interrupt or timeout.
     * 等待完成或因中断或超时而中止
     * @param timed true if use timed waits
     * @param nanos time to wait, if timed
     * @return state upon completion
     */
    private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            //如果调用get()的线程被中断了，就从等待的线程栈中移除这个等待节点，然后抛出中断异常
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            //如果s > COMPLETING，表示任务已经执行结束，或者发生异常结束了，就不会阻塞，直接返回任务状态
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            //如果s == COMPLETING，表示任务马上将要结束(正常/异常)，但是结果还没有保存到outcome字段，当前线程让出执行权，给其他线程先执行
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            //走到这里说明 这一轮的检查中发现任务没有执行完毕（或者走到这里是刚刚执行完毕，但是恰恰没有发现） 如果q=null,就创建一个等待节点（会记录当前线程）
            else if (q == null)
                q = new WaitNode();
            // 如果这个等待节点还没有加入等待队列，不过请注意是加入队列头！！！为什么添加到头部，因为不用去遍历找队尾，直接cas即可
            // 为什么要有队列？因为可能同时有多个线程想要当前future的执行结果
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q);
            //如果设置了超时等待时间
            else if (timed) {
                nanos = deadline - System.nanoTime();
                //超时了
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                //还没有超时
                LockSupport.parkNanos(this, nanos);
            }
            //无限阻塞，等待唤醒 任务执行结束会来唤醒
            else {
                LockSupport.park(this);
            }
        }
    }

    /**
     * Tries to unlink a timed-out or interrupted wait node to avoid
     * accumulating garbage.  Internal nodes are simply unspliced
     * without CAS since it is harmless if they are traversed anyway
     * by releasers.  To avoid effects of unsplicing from already
     * removed nodes, the list is retraversed in case of an apparent
     * race.  This is slow when there are a lot of nodes, but we don't
     * expect lists to be long enough to outweigh higher-overhead
     * schemes.
     * 移除队列中的等待线程  仅在异常或者超时时会进行此操作
     */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    if (q.thread != null)
                        pred = q;
                    else if (pred != null) {
                        pred.next = s;
                        if (pred.thread == null) // check for race
                            continue retry;
                    }
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long stateOffset;
    private static final long runnerOffset;
    private static final long waitersOffset;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = FutureTask.class;
            stateOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("state"));
            runnerOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("runner"));
            waitersOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("waiters"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

}
